﻿<template>
    <div class="esProductChannelPlanToday-container">
        <el-card shadow="hover">
            <el-form :model="state.queryParams" ref="queryForm" :inline="true">
                <el-form-item :label-width='70' label="商户名称">
                    <el-select :clearable='true' class='ml10' v-model="state.queryParams.merchantId"
                               placeholder="请选择" filterable>
                        <el-option v-for='item in state.merchantDict' :key='item.value' :label='item.label'
                                   :value='item.value'/>
                    </el-select>
                </el-form-item>
                <el-form-item :label-width='70' label="渠道名称">
                    <el-select :clearable='true' class='ml10' v-model="state.queryParams.channelId" placeholder="请选择"
                               filterable>
                        <el-option v-for='item in state.channelDict' :key='item.value' :label='item.label'
                                   :value='item.value'/>
                    </el-select>
                </el-form-item>
                <el-form-item :label-width='70' label='省份'>
                    <el-select :clearable='true' class='ml10' v-model='state.queryParams.province' placeholder='请选择'
                               filterable>
                        <el-option v-for='item in optionDict.provinceDict' :key='item.value' :label='item.label'
                                   :value='item.value'/>
                    </el-select>
                </el-form-item>
                <el-form-item :label-width='70' label="Key" prop="productChannelCode">
                    <el-input placeholder="Key" clearable class='ml10' @keyup.enter="handleQuery"
                              v-model="state.queryParams.productChannelCode"/>
                </el-form-item>
                <el-form-item :label-width='70' label="大Key" prop="productCategoryCode">
                    <el-input placeholder="大Key" clearable class='ml10' @keyup.enter="handleQuery"
                              v-model="state.queryParams.productCategoryCode"/>
                </el-form-item>
                <el-form-item :label-width='70' label="产品名称" prop="productName">
                    <el-input class='ml10' placeholder="产品名称" clearable @keyup.enter="handleQuery"
                              v-model="state.queryParams.productName"/>
                </el-form-item>
                <el-form-item :label-width='70' label='日期'>
                    <el-date-picker class='ml10' v-model='state.queryParams.selectDate' type='date' :clearable="false"
                                    date-format="YYYY/MM/DD"
                                    value-format="YYYY-MM-DD" placeholder='日期' :disabled-date="disabledDate"/>
                </el-form-item>
                <el-form-item>
                    <el-button-group>
                        <el-button type="primary" icon="ele-Search" @click="handleQuery" :loading="state.loading"
                                   v-auth="'esProductChannelPlanToday:query'"> 查询
                        </el-button>
                        <el-button icon="ele-Refresh" @click="resetQuery" v-auth="'esProductChannelPlanToday:query'"> 重置
                        </el-button>
                    </el-button-group>
                </el-form-item>
            </el-form>
        </el-card>

        <el-card shadow="hover" style="margin-top: 8px">
            <div style="margin: -8px 0 10px 0;">
                <el-button type="success" plain icon="ele-Plus" @click="openAddEsProductChannelPlanToday"
                           v-auth="'esProductChannelPlanToday:add'"> 新增
                </el-button>
            </div>
            <el-table :data="state.data" style="width: 100%" v-loading="state.loading" tooltip-effect="light"
                      row-key="id"
                      border stripe highlight-current-row>
                <el-table-column header-align="center" type="index" label="序号" width="55" align="center"/>
                <el-table-column header-align="center" prop="executionDate" width="100" label="执行日期"
                                 show-overflow-tooltip>
                    <template #default='scope'>
                        {{ scope.row.executionDate.substring(0, 10) }}
                    </template>
                </el-table-column>
                <el-table-column header-align="center" prop="merchantName" width="100" label="商户名称"
                                 show-overflow-tooltip/>
                <el-table-column header-align="center" prop="productName" min-width="330" label="产品名称"
                                 show-overflow-tooltip>
                    <template #default="scope">
						<span :class='productClassObject(Number(scope.row.status))'>
                           {{scope.row.productName}}
                        </span>
                    </template>
                </el-table-column>
                <el-table-column header-align="center" prop="channelName" width="100" label="渠道名称"
                                 show-overflow-tooltip/>
                <el-table-column header-align="center" prop="productChannelCode" width="80" label="Key"
                                 align="center"
                                 show-overflow-tooltip/>
                <el-table-column header-align="center" prop="productCategoryCode" width="80" label="大Key"
                                 align="center"
                                 show-overflow-tooltip/>
                <el-table-column header-align="center" prop="operatorPlatform" label="运营商" width="90" align="center"
                                 show-overflow-tooltip>
                    <template #default="scope">
                        <template v-if="scope.row.operatorPlatform !== -1">
                            <el-tag :type="getOperatorTagType(scope.row.operatorPlatform)">
                                {{ getOperatorLabel(scope.row.operatorPlatform) }}
                            </el-tag>
                        </template>
                        <span v-else></span> <!-- 无值时显示空白 -->
                    </template>
                </el-table-column>
                <el-table-column header-align='center' label="请求数" align='right' show-overflow-tooltip width="80">
                    <template #default="scope">
                        {{ scope.row.requestTime }}/{{ scope.row.requestLimit }}
                    </template>
                </el-table-column>
                <el-table-column header-align='center' label="用户数" align='right' show-overflow-tooltip width="80">
                    <template #default="scope">
                        {{ scope.row.subscribeUser }}/{{ scope.row.userLimit }}
                    </template>
                </el-table-column>
                <el-table-column header-align='center' label="渠道用户数" align='right' width="110"
                                 show-overflow-tooltip>
                    <template #default="scope">
                        {{ scope.row.channelSubscribeUser }}
                    </template>
                </el-table-column>
                <el-table-column header-align='center' label='订购转化率' align='right' width="110"
                                 show-overflow-tooltip>
                    <template #default='scope'>
						<span
                            :class='classObject(Number((scope.row.requestTime == 0 ? 0 : (scope.row.subscribeUser ?? 0) / scope.row.requestTime * 100).toFixed(0)))'>
                            {{
                                (scope.row.requestTime == 0 ? 0 : (scope.row.subscribeUser ?? 0) / scope.row.requestTime * 100).toFixed(2)
                            }}%</span>
                    </template>
                </el-table-column>
                <el-table-column header-align='center' label='渠道转化率' align='right' width="110"
                                 show-overflow-tooltip>
                    <template #default='scope'>
						<span
                            :class='classObject(Number((scope.row.requestTime == 0 ? 0 : (scope.row.channelSubscribeUser ?? 0) / scope.row.requestTime * 100).toFixed(0)))'>
                            {{
                                (scope.row.requestTime == 0 ? 0 : (scope.row.channelSubscribeUser ?? 0) / scope.row.requestTime * 100).toFixed(2)
                            }}%</span>
                    </template>
                </el-table-column>
                <el-table-column header-align="center" prop="arrivalType" label="到量类型" align="center"
                                 show-overflow-tooltip width="100">
                    <template #default="scope">
                        <el-tag type="info" v-if="scope.row.arrivalType === 1">请求数</el-tag>
                        <el-tag type="success" v-else-if="scope.row.arrivalType === 2">用户数</el-tag>
                    </template>
                </el-table-column>
                <el-table-column header-align='center' label="状态" align="center" show-overflow-tooltip>
                    <template #default="scope">
                        <div @click="changeStatus(scope.row)">
                            <el-switch
                                v-model="scope.row.status"
                                :active-value="1"
                                :inactive-value="scope.row.status <= 2 ? 2 : 4"
                                size="small"
                                :style="getSwitchStyle(scope.row.status)"
                                v-auth="'esProductChannelPlanToday:update'"
                            />
                        </div>
                    </template>
                </el-table-column>
                <el-table-column header-align="center" prop="updateStatusTime" width="160" label="状态更新时间"
                                 show-overflow-tooltip/>
                <el-table-column header-align="center" prop="province" label="开通省份" align="center"
                                 show-overflow-tooltip width="90"/>
                <el-table-column header-align="center" prop="screenCity" label="屏蔽城市" align="center"
                                 show-overflow-tooltip width="120"/>
                <el-table-column header-align="center" prop="endTime" label="时间范围" align="center"
                                 show-overflow-tooltip width="150">
                    <template #default="scope">
                        {{
                            (scope.row.startTime.substring(11, 16) == "00:00" && scope.row.endTime.substring(11, 16) == "23:59") ? "全天24H" : scope.row.startTime.substring(11, 19) + ' - ' + scope.row.endTime.substring(11, 19)
                        }}
                    </template>
                </el-table-column>
                <el-table-column header-align="center" prop="controlLevel" label="管控级别" show-overflow-tooltip
                                 width="90" align="center"/>
                <el-table-column header-align="center" prop="createTime" width="160" label="创建时间"
                                 show-overflow-tooltip/>
                <el-table-column label="操作" width="90" align="center" fixed="right" show-overflow-tooltip>
                    <template #default="scope">
                        <el-button size="small" text type="primary"
                                   @click="openEditEsProductChannelPlanToday(scope.row)"
                                   v-auth="'esProductChannelPlanToday:update'"> 编辑
                        </el-button>
                        <el-button size="small" text type="danger" @click="delEsProductChannelPlanToday(scope.row)"
                                   v-auth="'esProductChannelPlanToday:delete'"> 删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination @size-change="onHandleSizeChange" @current-change="onHandleCurrentChange" class="mt15"
                           :page-sizes="[20, 50, 100]" v-model:current-page="state.queryParams.pageNum" background
                           v-model:page-size="state.queryParams.pageSize"
                           layout="total, sizes, prev, pager, next, jumper"
                           :total="state.total"/>
            <EditEsProductChannelPlanToday ref="editEsProductChannelPlanTodayRef" :title="state.editTitle"/>
        </el-card>
    </div>
</template>

<script lang="ts" setup name="esProductChannelPlanToday">

import {onMounted, onUnmounted, reactive, ref} from 'vue';
import {ElMessageBox, ElMessage} from 'element-plus';
import {optionDict} from '/@/const/dict.ts';
import mittBus from '/@/utils/mitt';
import EditEsProductChannelPlanToday
    from '/@/views/exocytosis/operate/productChannelPlanToday/component/editEsProductChannelPlanToday.vue';
import {EsProductChannelPlanToday, sysBaseDict} from '/@/api/models';
import SysEsProductChannelPlanTodayApi from '/@/api/exocytosis/productChannelPlanToday';
import SysEsMerchantApi from '/@/api/exocytosis/merchant';
import SysEsChannelApi from '/@/api/exocytosis/channel';
import {todayDate} from "/@/utils/dateHelper";

// 定义变量内容
const editEsProductChannelPlanTodayRef = ref<InstanceType<typeof EditEsProductChannelPlanToday>>();
const state = reactive({
    loading: false,
    data: [] as Array<EsProductChannelPlanToday>,
    total: 0 as any,
    queryParams: {
        merchantId: undefined,
        channelId: undefined,
        productName: undefined,
        province: undefined,
        selectDate: todayDate(),
        productChannelCode: undefined,
        productCategoryCode: undefined,
        pageNum: 1,
        pageSize: 20,
    },
    editTitle: '',
    merchantDict: [] as sysBaseDict[],
    channelDict: [] as sysBaseDict[],
});

onMounted(async () => {
    await merchantDictQuery();
    await channelDictQuery();
    mittBus.on('submitRefresh', () => {
        handleQuery();
    });
});

onUnmounted(() => {
    mittBus.off('submitRefresh');
});

// 查询操作
const handleQuery = async () => {
    state.loading = true;
    const res = await SysEsProductChannelPlanTodayApi().queryRecord(state.queryParams);
    state.data = res.data.result?.items ?? [];
    state.total = res.data.result?.total;
    state.loading = false;
};

// 重置操作
const resetQuery = () => {
    // 1. 批量重置为undefined
    const keepKeys: string[] = ['pageNum', 'pageSize', 'selectDate']; // 声明需要保留的字段
    Object.keys(state.queryParams).forEach(key => {
        if (!keepKeys.includes(key))
            state.queryParams[key] = undefined;
    });
    // 2. 单独处理日期
    state.queryParams.selectDate = todayDate();
    state.data = [];
};

// 打开新增页面
const openAddEsProductChannelPlanToday = () => {
    state.editTitle = '添加';
    editEsProductChannelPlanTodayRef.value?.openDialog({
        status: 1,
        requestLimit: 0,
        userLimit: 0,
        arrivalType: 1,
        controlLevel: 0,
        phoneUniqueMonthly: 6,
        dailyStartHour: 8,
        dailyEndHour: 23,
        provinceList: [{}]
    }, 'add');
};

// 打开编辑页面
const openEditEsProductChannelPlanToday = (row: EsProductChannelPlanToday) => {
    state.editTitle = '编辑';
    editEsProductChannelPlanTodayRef.value?.openDialog(row, 'edit');
};

// 删除
const delEsProductChannelPlanToday = (row: any) => {
    ElMessageBox.confirm(`确定删除省份为：【${row.province}】Key为：【${row.productChannelCode}】?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    })
        .then(async () => {
            let res = await SysEsProductChannelPlanTodayApi().deletePost({
                id: row.id,
                executionDate: row.executionDate
            });
            if (res.data.resCode != '0000')
                ElMessage.error(res.data.resMessage);
            else
                ElMessage.success("删除成功");
            await handleQuery();
        })
        .catch(() => {
        });
};

// 改变页面容量
const onHandleSizeChange = (val: number) => {
    state.queryParams.pageSize = val;
    handleQuery();
};

// 改变页码序号
const onHandleCurrentChange = (val: number) => {
    state.queryParams.pageNum = val;
    handleQuery();
};

// 日期不可选范围
const disabledDate = (time: Record<string, any>): boolean => {
    const today = new Date(); // 获取今天的日期
    today.setHours(0, 0, 0, 0); // 将时间设置为当天的零点
    return time.getTime() > today.getTime(); // 禁用今天之后的所有日期
}

// 商户列表
const merchantDictQuery = async () => {
    await SysEsMerchantApi().queryAll().then((res) => {
        if (res.data.resCode === '0000')
            state.merchantDict = res.data.result ?? [];
    });
};

// 渠道列表
const channelDictQuery = async () => {
    await SysEsChannelApi().queryAll().then((res) => {
        if (res.data.resCode === '0000')
            state.channelDict = res.data.result ?? [];
    });
};

const classObject = (retainRate: number) => {
    let colorClass = '';
    if (retainRate >= 35) {
        colorClass = 'text-success';
    } else if (retainRate >= 15) {
        colorClass = 'text-warning';
    } else {
        colorClass = 'text-danger';
    }
    return colorClass;
};

// 修改状态
const changeStatus = (row: EsProductChannelPlanToday) => {
    let onStatus = row.status == 1 ? '一键启动' : row.status == 2 ? '一键关停' : '';
    row.status = row.status == 1 ?  1 : 4;
    ElMessageBox.confirm(`是否${onStatus}（涉及到：当日计划）？`, '', {
            title: '提示',
            confirmButtonText: '确定',
            cancelButtonText: '取消',
        }
    )
        .then(() => {
            SysEsProductChannelPlanTodayApi()
                .setStatusPost(row)
                .then((res) => {
                    if (res.data.resCode == '0000') {
                        ElMessage.success(`${onStatus}状态设置成功`);
                    } else {
                        row.status = row.status == 1 ? 2 : 1;
                        ElMessage.error(`${onStatus}状态设置失败`);
                    }
                })
                .catch(() => {
                    row.status = row.status == 1 ? 2 : 1;
                });
        })
        .catch(() => {
            row.status = row.status == 1 ? 2 : 1;
        })
};

// 获取运营商标签文本
const getOperatorLabel = (value: number) => {
    const item = optionDict.operatorPlatformDict.find(item => item.value === value)
    return item?.label || '未知'
}

// 获取标签类型
const getOperatorTagType = (value: number) => {
    const item = optionDict.operatorPlatformDict.find(item => item.value === value)
    return item?.type || 'danger'
}

const getSwitchStyle = (status) => {
    return status <= 2
        ? '--el-switch-on-color: #67C23A; --el-switch-off-color: red'
        : '--el-switch-on-color: #67C23A; --el-switch-off-color: #E6A23C';
};

const productClassObject = (status: number) => {
    let colorClass = '';
    if (status === 2 || status === 4) {
        colorClass = 'text-info';
    }
    return colorClass;
};
</script>

<style scoped lang='scss'>
.text-primary {
    color: var(--el-color-primary);
}

.text-success {
    color: var(--el-color-success);
}

.text-info {
    color: var(--el-color-info);
}

.text-warning {
    color: var(--el-color-warning);
}

.text-danger {
    color: var(--el-color-danger);
}
</style>
